import 'package:fluent_ui/fluent_ui.dart';

///订阅者回调类型
typedef EventCallback = void Function(dynamic arg);

///事件总线
class EventBus {
  EventBus._();

  static final EventBus _singleton = EventBus._();

  ///工厂构造函数
  factory EventBus() => _singleton;

  //事件订阅者队列
  final _eMap = <dynamic, List<EventCallback>>{};

  ///添加订阅者
  void on(final dynamic eventName, final EventCallback callback) {
    debugPrint('添加订阅者: $eventName=>$callback');
    if (eventName == null) {
      return;
    }
    _eMap[eventName] ??= <EventCallback>[];
    _eMap[eventName]?.add(callback);
  }

  ///移除订阅者
  void off(final dynamic eventName, [final EventCallback? callback]) {
    debugPrint('移除订阅者: $eventName=>$callback');
    if (eventName == null) {
      return;
    }
    if (callback == null) {
      _eMap[eventName] = [];
    } else {
      final items = _eMap[eventName];
      if (items == null || items.isEmpty) {
        return;
      }
      items.remove(callback);
    }
  }

  ///触发事件,事件触发后该事件所有订阅者会被调用
  void emit(final dynamic eventName, [final dynamic arg]) {
    debugPrint('触发事件: $eventName=>$arg');
    if (eventName == null) {
      return;
    }
    final items = _eMap[eventName];
    if (items == null || items.isEmpty) {
      return;
    }
    final len = items.length - 1;
    for (var i = len; i > -1; --i) {
      items[i].call(arg);
    }
  }
}

///事件总线单例
final eventBus = EventBus();
